package com.atguigu.tingshu.comment.consumer;

import com.atguigu.tingshu.comment.service.CommentService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 监听评论的审核消息,审核评论的内容
 */
@Component
@Log4j2
public class TrackCommentConsumer {

    @Autowired
    private CommentService commentService;

    /**
     * 接受消息审核评论
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "comment_queue")
    public void TrackCommentConsumer(Channel channel, Message message){
        //获取消息的内容
        String commentId = new String(message.getBody());
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //消费消息
        try {
            //审核评论
            commentService.checkCommentContent(commentId);
            //确认
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            if(messageProperties.getRedelivered()){
                e.printStackTrace();
                log.error("审核评论失败,评论的id为:" + commentId);
                channel.basicReject(deliveryTag, false);
            }else{
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
